package com.zelin.jwt;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.junit.Test;

import java.util.Date;

public class JwtTest {
    //1.创建Token
    @Test
    public void testA(){
        JwtBuilder jwtBuilder = Jwts.builder().setId("6666")
                .setSubject("testA")
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + 300 * 1000))
                .signWith(SignatureAlgorithm.HS256, "zelin");
        String compact = jwtBuilder.compact();
        System.out.println("compact = " + compact);
    }
    //2.解析Token
    @Test
    public void testAA(){
        String token="eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI2NjY2Iiwic3ViIjoidGVzdEEiLCJpYXQiOjE1OTU4NDk0NDMsImV4cCI6MTU5NTg0OTc0M30.-pKEgIIXHDyt_eqhY4DId_gbQlCums76m8E936gom7Q";
        Claims claims = Jwts.parser().setSigningKey("zelin").parseClaimsJws(token).getBody();
        String id = claims.getId();
        Date issuedAt = claims.getIssuedAt();
        Date expiration = claims.getExpiration();
        String subject = claims.getSubject();
        System.out.println("id = " + id);
        System.out.println("issuedAt = " + issuedAt);
        System.out.println("expiration = " + expiration);
        System.out.println("subject = " + subject);
    }
    //3.创建token,携带数据
    @Test
    public void testB(){
        JwtBuilder jwtBuilder = Jwts.builder().setId("5555")
                .setSubject("testB")
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis()+1200 *1000))
                .signWith(SignatureAlgorithm.HS256, "zelin")
                .claim("roles", "admin");
        String compact = jwtBuilder.compact();
        System.out.println("compact = " + compact);
    }
    //4.解析Token,携带数据
    @Test
    public  void testBB(){
        String token="eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI1NTU1Iiwic3ViIjoidGVzdEIiLCJpYXQiOjE1OTU4NDk4MzgsImV4cCI6MTU5NTg1MTAzOCwicm9sZXMiOiJhZG1pbiJ9.vNYJp7tpShfJv8LOkFJ9cUSvjcQtDU9jqeav4RWdOOU";
        Claims claims = Jwts.parser().setSigningKey("zelin").parseClaimsJws(token).getBody();
        String id = claims.getId();
        String subject = claims.getSubject();
        Date issuedAt = claims.getIssuedAt();
        Date expiration = claims.getExpiration();
        String roles = (String) claims.get("roles");
        System.out.println("id = " + id);
        System.out.println("subject = " + subject);
        System.out.println("issuedAt = " + issuedAt);
        System.out.println("expiration = " + expiration);
        System.out.println("roles = " + roles);
    }
}
